// 加载Express模块
const express = require('express');

// 加载MySQL模块
const mysql = require('mysql');

// 加载bodyParser模块
const bodyParser = require('body-parser');


// 创建MySQL连接池
const pool = mysql.createPool({
  host: '127.0.0.1',   //MySQL服务器地址
  port: 3306,          //MySQL服务器端口号
  user: 'root',        //数据库用户的用户名
  password: 'root',        //数据库用户密码
  database: 'anta_mall',    //数据库名称
  connectionLimit: 20, //最大连接数
  charset: 'utf8'      //数据库服务器的编码方式
});

// 创建服务器对象
const server = express();

server.use(express.json())
server.use(express.urlencoded({
  extended: true
}));


// 加载CORS模块
const cors = require('cors');

// 使用CORS中间件
server.use(cors({
  origin: '*'
}));


//用户注册接口-手机号
server.post('/registerByPhone', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let phone = req.body.phone;
  let username=req.body.phone;
  let password = req.body.password;
  //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(id) AS count FROM user WHERE phone=?';
  pool.query(sql, [phone], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'INSERT user(username,phone,password) VALUES(?,?,?)';
      pool.query(sql, [username,phone, password], (error, results) => {
        if (error) throw error;
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: '手机号已存在', code: 201 });
    }
  });
});

//用户注册接口-邮箱
server.post('/registerByEmail', (req, res) => {
    //console.log(md5('12345678'));
    // 获取用户名和密码信息
    let email = req.body.email;
    let username=req.body.email;
    let password = req.body.password;
    //以username为条件进行查找操作，以保证用户名的唯一性
    let sql = 'SELECT COUNT(id) AS count FROM user WHERE email=?';
    pool.query(sql, [email], (error, results) => {
      if (error) throw error;
      let count = results[0].count;
      if (count == 0) {
        // 将用户的相关信息插入到数据表
        sql = 'INSERT user(username,email,password) VALUES(?,?,?)';
        pool.query(sql, [username,email, password], (error, results) => {
            // console.log(results)
          if (error) throw error;
          res.send({ message: 'ok', code: 200 });
        })
      } else {
        res.send({ message: '邮箱已存在', code: 201 });
      }
    });
  });
// 用户登录接口
server.post('/login', (req, res) => {
    console.log(res)
  //获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.password;
//   console.log(username)
//   console.log(password)
  // SQL语句
  let sql = 'SELECT * FROM user WHERE username=? AND password=?';
  console.log(sql)
  pool.query(sql, [username, password], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //登录失败
      res.send({message:'用户名或密码错误',code:201});
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:results[0]});
    }
  });

});
//加入购物车接口
server.post('/insert', (req, res) => {
    let uid = req.body.uid;//商品名称
    let cache_title = req.body.cache_title;//商品名称
    let cache_price = req.body.cache_price;//售卖价格，现价
    let market_price = req.body.market_price;//原价
    let cache_image = req.body.cache_image;//产品图片
    let cache_attr = req.body.cache_attr;//产品规格
    let add_num=req.body.add_num//添加数量
    let add_price=cache_price
    //以username为条件进行查找操作，以保证用户名的唯一性
    let sql = 'INSERT INTO `anta_mall`.`goods` (`cache_title`, `cache_price`, `market_price`, `cache_image`, `cache_attr`) VALUES (?,?,?,?,?)';
    pool.query(sql, [cache_title,cache_price,market_price,cache_image,cache_attr], (error, results) => {
      if (error) throw error;
      let id_goods=results.insertId
      if (id_goods >0) {
        // 将用户的相关信息插入到数据表
        sql = 'INSERT INTO `anta_mall`.`cart` ( `uid`, `id_goods`, `add_num`,  `add_price`) VALUES (?,?,?,?)';
        pool.query(sql, [uid,id_goods,add_num,add_price], (error, results) => {
          if (error) throw error;
          let affectedRows=results.affectedRows
          if(affectedRows<=0){
            res.send({ message: '加入购物车失败', code: 201 }); 
          }
          res.send({ message: 'ok', code: 200 });
});
         
      } else {
        res.send({ message: '加入购物车失败', code: 201 });
      }
    });
  });
  //获取购物车列
server.post('/getCart', (req, res) => {
     //登录用户ID
  let uid = req.body.uid;
  // SQL语句
  let sql = `select cart.*,goods.* from cart
  INNER JOIN goods ON cart.id_goods=goods.id
  WHERE cart.uid=?`;
//   console.log(sql)
//   console.log(uid)
  pool.query(sql, [uid], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //查询失败
      res.send({message:'查询失败',code:201});
    } else {                 //查询成功
      res.send({message:'ok',code:200,result:results});
    }
  });
  });
// 指定服务器对象监听的端口号
server.listen(3000, () => {
  console.log('server is running...');
});